package com.songqi.common.security.auth;

import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 模仿 UsernamePasswordAuthenticationFilter 获取前端传递的 手机号、验证码
 * @author songqi(13776346982)
 */
public class SmsCodeAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

    /**
     * 参数名
     */
    public static final String MOBILE_KEY = "phone";
    public static final String CODE_KEY = "verifyCode";

    private static final AntPathRequestMatcher DEFAULT_ANT_PATH_REQUEST_MATCHER = new AntPathRequestMatcher("/verifyCode/login", "POST");

    public SmsCodeAuthenticationFilter() {
        // 表示这个 Filter 拦截 /verifyCode/login 接口
        super(DEFAULT_ANT_PATH_REQUEST_MATCHER);
    }



 




    /**
     * 用来获取前端传递的手机号和验证码，然后调用 authenticate 方法进行认证
     * @param request
     * @param response
     * @return
     * @throws AuthenticationException
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
        if (!"POST".equals(request.getMethod())) {
            throw new AuthenticationServiceException("Authentication method not supported:  " + request.getMethod());
        }else{
            //从请求中获取参数值
            String phone = request.getParameter(MOBILE_KEY);
            phone = phone != null ? phone : "";
            phone = phone.trim();
            String verifyCode = request.getParameter(CODE_KEY);
            verifyCode = verifyCode != null ? verifyCode : "";
            verifyCode = verifyCode.trim();
            // 封装手机号、验证码，后面框架会从中拿到 手机号， 调用我们的 LoginPhoneService 获取用户
            SmsCodeAuthenticationToken authRequest  = new SmsCodeAuthenticationToken(phone, verifyCode);
            //设置ip、sessionId信息
            setDetails(request, authRequest);
            return this.getAuthenticationManager().authenticate(authRequest);
        }

    }
 
    protected void setDetails(HttpServletRequest request, SmsCodeAuthenticationToken authRequest) {
        authRequest.setDetails(this.authenticationDetailsSource.buildDetails(request));
    }


}
